package com.unionftech.common.recaptcha

import android.app.Activity
import android.app.Application
import android.text.TextUtils
import com.google.android.recaptcha.Recaptcha
import com.google.android.recaptcha.RecaptchaAction
import com.google.android.recaptcha.RecaptchaTasksClient
import com.unionftech.common.CommonConstants
import com.unionftech.common.bean.CaptchaType
import com.unionftech.common.utils.LogUtils
import java.util.concurrent.Executors

class RecaptchaUtil private constructor() {
    private lateinit var recaptchaClient: RecaptchaTasksClient
    private var mCaptchaType: CaptchaType? = null

    companion object {
        private const val TAG = "RecaptchaUtil"
        private const val API_SITE_KEY = CommonConstants.Config.GOOGLE_RECAPTCHA_KEY
        const val RECAPTCHA_CANCEL = "recaptcha_cancel"
        const val ACTION_SEND_CODE = "sendcode"
        const val ACTION_LOGIN = "login"
        const val ACTION_SING_UP = "signup"

        @Volatile
        private var instance: RecaptchaUtil? = null

        @JvmStatic
        fun getInstance() = instance ?: synchronized(this) {
            instance ?: RecaptchaUtil().also {
                instance = it
            }
        }
    }

    /**
     * 初始化 RecaptchaTasksClient实例，应该放在模块初始化里，避免在界面上初始化，造成界面卡顿
     */
    fun init(application: Application) {
        Executors.newSingleThreadExecutor().submit {
            Recaptcha.fetchTaskClient(application, API_SITE_KEY).addOnSuccessListener { client ->
                recaptchaClient = client
            }.addOnFailureListener { e ->
                e.printStackTrace()
                LogUtils.e(TAG, "init error: ${e.message}")
            }
        }
    }

    /**
     * google评分验证
     */
    fun verifyWithGoogle(
        activity: Activity, action: RecaptchaAction, listener: (
            CaptchaType, String?, ((captchaResult: Boolean) -> Unit)?
        ) -> Unit
    ) {
        if (!::recaptchaClient.isInitialized) {
            LogUtils.e(TAG, "init first !!!")
            verifyWithNetease(activity, listener)
            return
        }
        recaptchaClient.executeTask(action, 5000L).addOnSuccessListener { token ->
            LogUtils.d(TAG, "google verify token-->${token}")
            mCaptchaType = CaptchaType.GOOGLE
            listener.invoke(CaptchaType.GOOGLE, token, null)
        }.addOnFailureListener { e ->
            LogUtils.e(TAG, "verifyWithRecaptcha error: ${e.message}")
            verifyWithNetease(activity, listener)
        }
    }

    /**
     * 网易易盾滑块验证
     */
    fun verifyWithNetease(
        activity: Activity, listener: (
            CaptchaType, String?, ((captchaResult: Boolean) -> Unit)?
        ) -> Unit
    ) {
        if (mCaptchaType == CaptchaType.ALIYUN) {
            AliyunCaptchaUtil.getInstance().destroy()
        }
        mCaptchaType = CaptchaType.NETEASE
        YiDunCaptchaUtil.getInstance().verify(activity) { neteaseToken, error ->
            LogUtils.d(TAG, "Netease verify token-->${neteaseToken}")
            //如果网易易盾出错切换阿里云滑块
            if (error != null) {
                YiDunCaptchaUtil.getInstance().destroy()
                verifyWithAliyun(activity) { _, token, jsCallBack ->
                    listener.invoke(CaptchaType.ALIYUN, token, jsCallBack)
                }
            } else {
                listener.invoke(CaptchaType.NETEASE, neteaseToken, null)
            }
        }
    }

    /**
     * 阿里云滑块验证
     */
    fun verifyWithAliyun(
        activity: Activity,
        listener: (
            CaptchaType, token: String?, jsCallBack: ((captchaResult: Boolean) -> Unit)?
        ) -> Unit,
    ) {
        if (mCaptchaType == CaptchaType.NETEASE) {
            YiDunCaptchaUtil.getInstance().destroy()
        }
        mCaptchaType = CaptchaType.ALIYUN
        AliyunCaptchaUtil.getInstance().verify(activity) { token, jsCallBack ->
            if (TextUtils.isEmpty(token)) {
                jsCallBack?.invoke(false)
            } else {
                LogUtils.d(TAG, "Aliyun verify token-->${token}")
                listener.invoke(CaptchaType.ALIYUN, token, jsCallBack)
            }
        }
    }

    fun destroy() {
        YiDunCaptchaUtil.getInstance().destroy()
        AliyunCaptchaUtil.getInstance().destroy()
    }
}